<template>
    <el-container>
        <el-header class="header-tabs">
            <el-tabs type="card" v-model="groupId" @tab-change="tabChange">
				<el-tab-pane label="日账单列表" name="1"></el-tab-pane>
				<el-tab-pane label="对账单列表" name="2"></el-tab-pane>
				<el-tab-pane label="扣款单列表" name="0"></el-tab-pane>
			</el-tabs>
        </el-header>
        <!-- 扣款单 -->
        <el-header v-if="groupId==0">
            <div class="right-panel-search">
                <div class="search-input">单号</div>
                <el-input v-model="debit.order_no" placeholder="请输入单号" clearable @change="upsearch" />
                <div class="search-input">工厂</div>
                <el-select v-model="debit.supplier_id" filterable placeholder="请选择工厂" clearable>
                    <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"/>
                </el-select>
                <div class="search-input">扣款类型</div>
                <el-select v-model="debit.slip_type_id" placeholder="类型" clearable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="1">
                    <el-option v-for="item in deductionList" :key="item.id" :label="item.title" :value="item.id"/>
                </el-select>
                <div class="search-input">状态</div>
                <el-select v-model="debit.is_bill" placeholder="状态" clearable>
                    <el-option label="未生成" :value="0"/>
                    <el-option label="已生成" :value="1"/>
                </el-select>
                <el-date-picker v-model="debit.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="medium" style="width:250px" :value-format="'YYYY-MM-DD'" />
                <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="add" v-auth="'kou.add'">添加扣款单</el-button>
            </div>
        </el-header>
        <el-main class="nopadding" v-if="groupId==0">
            <scTable ref="table" :apiObj="apiObj" stripe remoteSort remoteFilter border @selection-change="selectionChange" :params="query" show-summary>
                <el-table-column type="selection" fixed width="50"></el-table-column>
                <el-table-column label="扣款单号" align="center" width="150">
                    <template #default="scope">
                        <div>{{scope.row.order_no}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="工厂" prop="referred_as" align="center"></el-table-column>
                <el-table-column label="日期" prop="order_time" align="center"></el-table-column>
                <el-table-column label="类型" prop="type_name" align="center"></el-table-column>
                <el-table-column label="金额" prop="money" align="center"></el-table-column>
                <el-table-column label="备注" align="center">
                    <template #default="scope">
                        <div>{{scope.row.remark}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.is_bill == 0" type="danger">未生成</el-tag>
                        <el-tag v-else type="success">已生成</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="图片" align="center">
                    <template #default="scope">
                        <el-image class="img" :src="scope.row.other_images[0]" :preview-src-list="scope.row.other_images" :initial-index="0" fit="cover" preview-teleported="true" hide-on-click-modal />
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" align="center" prop="create_time"></el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="80">
                    <template #default="scope">
                        <el-button-group style="display:flex;flex-direction:column">
                            <el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)" v-auth="'kou.edit'">编辑</el-button>
                            <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                                <template #reference>
                                    <el-button text type="danger" size="small" v-auth="'kou.delete'">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
        <!-- 日账单 -->
        <el-header v-if="groupId==1">
            <div class="right-panel-search">
                <div class="search-input">单号</div>
                <el-input v-model="daySearch.order_no" placeholder="请输入单号" clearable @change="upsearch" />
                <div class="search-input">工厂</div>
                <el-select v-model="daySearch.supplier_id" filterable placeholder="请选择工厂" clearable>
                    <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"/>
                </el-select>
                <div class="search-input">客户</div>
                <el-select v-model="daySearch.custom_id" filterable placeholder="请选择客户" clearable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="1">
                    <el-option v-for="item in customerList" :key="item.custom_id" :label="item.apply_name" :value="item.custom_id"/>
                </el-select>
                <div class="search-input">状态</div>
                <el-select v-model="daySearch.is_bill" placeholder="状态" clearable>
                    <el-option label="未生成" :value="0"/>
                    <el-option label="已生成" :value="1"/>
                </el-select>
                <el-date-picker v-model="daySearch.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="medium" style="width:250px" :value-format="'YYYY-MM-DD'" />
                <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
                <el-button type="primary" @click="openKou" :disabled="selection.length==0" v-auth="'dui.add'" v-if="daySearch.is_bill==0">生成对账单</el-button>
            </div>
        </el-header>
        <el-main class="nopadding" v-if="groupId==1">
            <scTable ref="table" :apiObj="billDay" stripe remoteSort remoteFilter border @selection-change="selectionChange" show-summary :params="query">
                <el-table-column type="selection" fixed width="50"></el-table-column>
                <el-table-column label="日账单编号" prop="order_no" align="center"></el-table-column>
                <el-table-column label="工厂" prop="referred_as" align="center"></el-table-column>
                <el-table-column label="客户" prop="custom_name" align="center"></el-table-column>
                <el-table-column label="下单数量" prop="order_num" align="center"></el-table-column>
                <el-table-column label="发货数量" prop="send_num" align="center"></el-table-column>
                <el-table-column label="入库数量" prop="storage_num" align="center"></el-table-column>
                <el-table-column label="金额" prop="money" align="center"></el-table-column>
                <el-table-column label="状态" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.is_bill==0" type="danger">未生成</el-tag>
                        <el-tag v-else type="success">已生成</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" align="center" prop="create_time"></el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="80">
                    <template #default="scope">
                        <el-button-group style="display:flex;flex-direction:column">
                            <el-button text type="primary" size="small" @click="table_bill(scope.row, scope.$index)">账单详情</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
        <!-- 对账单 -->
        <el-header v-if="groupId==2">
            <div class="right-panel-search">
                <div class="search-input">单号</div>
                <el-input v-model="master.order_no" placeholder="请输入单号" clearable @change="upsearch" />
                <div class="search-input">工厂</div>
                <el-select v-model="master.supplier_id" filterable placeholder="请选择工厂" clearable>
                    <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"/>
                </el-select>
                <div class="search-input">状态</div>
                <el-select v-model="master.status" placeholder="状态" clearable>
                    <el-option label="待确认" :value="0"/>
                    <el-option label="已确认" :value="1"/>
                </el-select>
                <el-date-picker v-model="master.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="medium" style="width:250px" :value-format="'YYYY-MM-DD'" />
                <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
            </div>
        </el-header>
        <el-main class="nopadding" v-if="groupId==2">
            <scTable ref="table" :apiObj="billMaster" stripe remoteSort remoteFilter border @selection-change="selectionChange" :params="query" show-summary>
                <el-table-column type="selection" fixed width="50"></el-table-column>
                <el-table-column label="对账单编号" prop="order_no" align="center"></el-table-column>
                <el-table-column label="工厂" prop="referred_as" align="center"></el-table-column>
                <el-table-column label="客户" prop="custom_list" align="center">
                    <template #default="scope">
                        <div v-for="(item, index) in scope.row.custom_list" :key="index">
                            {{ item }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="应付金额" prop="total_money" align="center"></el-table-column>
                <el-table-column label="扣款金额" prop="deduct_money" align="center"></el-table-column>
                <el-table-column label="实付金额" prop="meet_money" align="center"></el-table-column>
                <el-table-column label="状态" prop="send_count" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status==0" type="danger">未确认</el-tag>
                        <el-tag v-else type="success">已确认</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" align="center" prop="create_time"></el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="80">
                    <template #default="scope">
                        <el-button-group style="display:flex;flex-direction:column">
                            <el-button text type="primary" size="small" @click="table_dayDel(scope.row, scope.$index)" v-auth="'dui.detail'">账单详情</el-button>
                            <el-button text type="primary" size="small" @click="table_kouDel(scope.row, scope.$index)" v-auth="'kou.detail'">扣款单详情</el-button>
                            <el-button text type="primary" size="small" @click="table_detial(scope.row, scope.$index)" v-auth="'kou.exrport'">导出</el-button>
                            <el-popconfirm title="是否确认该结算单吗？" @confirm="confirm(scope.row, scope.$index)">
                                <template #reference>
                                    <el-button text type="primary" size="small" v-auth="'dui.confirm'" v-show="scope.row.status==0">确认</el-button>
                                </template>
                            </el-popconfirm>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
    </el-container>
    <print ref="pitDialog"></print>
    <save v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false" draggable></save>
    <kou-save v-if="dialog.kou" ref="kouDialog" @success="handleSuccess" @closed="dialog.kou = false" draggable :query="{supplier_id:supId,is_bill:0}"></kou-save>
    <day-save v-if="dialog.day" ref="dayDialog" @success="handleSuccess" @closed="dialog.day = false" draggable></day-save>
    <kou-detail v-if="dialog.detail" ref="detailDialog" @success="handleSuccess" @closed="dialog.detail = false" draggable></kou-detail>
    <bill-day v-if="dialog.bill" ref="billDialog" @success="handleSuccess" @closed="dialog.bill = false" draggable></bill-day>
</template>

<script>
import print from '../print.vue'
import BillDay from './billDay.vue';
import DaySave from './daySave.vue';
import KouDetail from './kouDetail.vue';
import KouSave from './kouSave.vue';
import save from "./save";
export default {
  components: { save,print, KouSave, DaySave, KouDetail, BillDay },
	name: 'user',
	data() {
		return {
			dialog: {
				save: false,
                pit:false,
                kou:false,
                day:false,
                detail:false,
                bill:false,
			},
			groupFilterText: '',
			group: [],
			apiObj: this.$API.inventory.getDeduction.lists,
			billDay: this.$API.inventory.BillDays,
			billMaster: this.$API.inventory.billMaster,
            query:{
                is_bill:0,
                status:0,
            },
            querys:{
                status:0,
                is_finance:0
            },
			selection: [],
			daySearch: {
                order_no:null,
				supplier_id: null,
				custom_id: null,
                is_bill:0
			},
            debit: {
                order_no:null,
				supplier_id: null,
                slip_type_id: null,
				custom_id: null,
				status: null,
				time: null,
                is_bill:0
			},
            master: {
                order_no:null,
				supplier_id: null,
				custom_id: null,
				time: null,
				status: 0,
			},
            applyList:[],
            customerList:[],
            deductionList:[],
            groupId: "1",
            supId:"",
		}
	},
    mounted() {
        this.getApply()
        this.getKeHu()
        this.getDeduc()
	},
	methods: {
		//添加
		add() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('add')
			})
		},
        // 日账单
        async print(){
            let ids = []
            this.selection.map(item=>{
                ids.push(item.order_no)
            })
            var reqData = { order_no_arr:ids };
            var res = await this.$API.print.createDayBill.post(reqData);
            if (res.code == 1) {
                this.$message.success("生成成功")
                this.$refs.table.refresh()
                // this.$refs.pitDialog.init(res.data);
            } else {
                this.$alert(res.message, "提示", { type: "error" });
            }
        },
        // 导出
        async table_detial(row){
            var res = await this.$API.inventory.cum.out.get({id:row.id});
            if (res.code == 1) {
                if(res.data.rows !=''){
                    const fileUrl = res.data.rows.url;
                    const link = document.createElement("a");
                    link.href = fileUrl;
                    link.download = fileUrl;
                    link.click();
                }else{
                    this.$alert("请求异常", "提示", { type: "error" });
                }
            } else {
                this.$alert(res.message, "提示", { type: "error" });
            }
        },
		//编辑扣款单
		table_edit(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			})
		},
		//删除扣款单
		async table_del(row, index) {
			var reqData = { id: row.id }
			var res = await this.$API.inventory.getDeduction.delete.post(reqData);
			if (res.code == 1) {
				//这里选择刷新整个表格 OR 插入/编辑现有表格数据
				this.$refs.table.tableData.splice(index, 1);
                this.$refs.table.refresh()
				this.$message.success("删除成功")
			} else {
				this.$alert(res.message, "提示", { type: 'error' })
			}
		},
		//搜索
		upsearch() {
            if(this.groupId == 0 ){
                this.$refs.table.upData(this.debit)
            }else if(this.groupId == 1){
                this.$refs.table.upData(this.daySearch)
            }else{
                this.$refs.table.upData(this.master)
            }
		},
        selectionChange(selection){
            this.selection = selection;
        },
		//本地更新数据
		handleSuccess(data, mode) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'set') {
				this.$refs.table.refresh()
			}
		},
        // 获取工厂
        async getApply(){
            var res = await this.$API.all.Apply.get({type:1});
            this.applyList = res.data;
        },
        // 获取客户
        async getKeHu(){
            var res = await this.$API.all.customer.get();
            this.customerList = res.data;
        },
        // 获取扣款原因
        async getDeduc(){
            var res = await this.$API.all.bill.get();
            this.deductionList = res.data;
        },
        tabChange(e){
            // this.selection = null
            this.groupId = e
            this.debit.supplier_id = null
            this.debit.custom_id = null
            this.debit.order_no = null
            this.debit.is_bill = 0

            this.daySearch.supplier_id = null
            this.daySearch.custom_id = null
            this.daySearch.is_bill = 0
            this.daySearch.order_no = null
            this.query.is_bill = 0
            
            this.master.supplier_id = null
            this.master.custom_id = null
            this.master.order_no = null
            this.master.status = 0
            this.querys.status = 0
        },
        // 选择日账单,弹窗选择扣款单
        openKou(){
            let factory = this.selection.map(item=>item.referred_as)
            let factoryName = factory.every(name => name === factory[0]);
            let a = this.selection.map(item=>item.supplier_id)
            this.supId = a[0]
            if(factoryName){
                this.dialog.kou = true
                this.$nextTick(() => {
                	this.$refs.kouDialog.open('add').setData(this.selection)
                })
            }else{
                this.$message.error("请选择同工厂生成对账单");
            }
        },
        // 对账单详情
        table_dayDel(row){
            this.dialog.day = true
			this.$nextTick(() => {
				this.$refs.dayDialog.open('edit').setData(row)
			})
        },
        async confirm(row) {
			var reqData = { id: row.id }
			var res = await this.$API.inventory.confirm.post(reqData);
			if (res.code == 1) {
                this.$refs.table.refresh()
				this.$message.success("确定成功")
			} else {
				this.$alert(res.message, "提示", { type: 'error' })
			}
		},
        // 日账单详情
        table_bill(row){
            this.dialog.bill = true
			this.$nextTick(() => {
				this.$refs.billDialog.open('edit').setData(row)
			})
        },
        // 扣款单详情
        table_kouDel(row){
            this.dialog.detail = true
			this.$nextTick(() => {
				this.$refs.detailDialog.open('edit').setData(row)
			})
        },
	}
}
</script>

<style>
.search-input {
	width: auto;
	font-size: 14px;
}
.img{
    width: 100px;
    height: 100%;
    margin-right: 5px;
}
</style>
